package com.imooc.oauth2.server.controller;

import java.security.Principal;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.imooc.commons.model.domain.ResultInfo;
import com.imooc.commons.utils.ResultInfoUtil;

/**
 * \* @author: bear
 * \* Date: 2021-07-11-16:08
 * \* describe:
 */
@RestController
@RequestMapping("oauth")
public class OAuthController {

	@Resource
	private TokenEndpoint endpoint;
	@Resource
	private HttpServletRequest request;

	@PostMapping("token")
	public ResultInfo postAccessToken(Principal principal, @RequestParam Map<String, String> parameters)
			throws HttpRequestMethodNotSupportedException {
		return custom(endpoint.postAccessToken(principal,parameters).getBody());
	}

	//返回自定义token
	private ResultInfo custom(OAuth2AccessToken accessToken) {
		DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken)accessToken;
		Map<String,Object> map = new LinkedHashMap<>(token.getAdditionalInformation());
		map.put("accessToken",token.getValue());
		map.put("expireIn",token.getExpiresIn());
		map.put("scopes",token.getScope());
		if (token.getRefreshToken() != null) {
			map.put("refreshToken", token.getRefreshToken().getValue());
		}
		return ResultInfoUtil.buildSuccess(request.getServletPath(), map);
	}
}
